package main

import (
	"fmt"
)

func writeData(data chan int,finish chan bool, num int)  {
	for i:=1;i<=2000;i++ {
		data <- i
	}
	finish <- true
	close(finish)
}

func writeRes(data chan int,resChan chan int,all chan bool,numGo chan int)  {
	num := <-data
	res := 0
	for i:=1;i<=num;i++ {
		res += i
	}
	resChan <- res
	if len(resChan)==2000 {
		all <- true
		close(all)
	}
	<-numGo
}

func main()  {
	var numChan chan int
	var isFinish chan bool
	var resChan chan int
	var numGo chan int
	var all chan bool
	
	numChan = make(chan int,2000)
	isFinish = make(chan bool,1)
	all = make(chan bool,1)
	resChan = make(chan int,2000)
	numGo = make(chan int,8)

	go writeData(numChan,isFinish,2000)
	for {
		if _,ok := <-isFinish; !ok {
			break
		}
	}
	// for i:=1;i<=2000;i++ {
	// 	fmt.Println(<-numChan)
	// }
	for i:=1;i<=2000;i++ {
		numGo <- i
		go writeRes(numChan,resChan,all,numGo)
	}

	for {
		if _,ok := <-all; !ok {
			break
		}
	}

	for i:=1;i<=2000;i++ {
		num := <-resChan
		fmt.Printf("结果的channel[%d]=%d\n",i,num)
	}
}
